<template>
  <view class="oreo-register">
    <view class="oreo">
      <image class="oreo-header" :src="ossImg('personal/oreo_header.png')" />
      <view
        class="oreo-body"
        :style="{ backgroundImage: `url(${ossImg('personal/oreo_body.png')})` }"
      >
        <image :src="ossImg('register/avatar.png')" />
        <view class="leading-none">
          <view>成为奥利奥会员</view>
          <view class="mt-11px">随时随地玩在一起</view>
        </view>
      </view>
    </view>
    <view class="privilege" :class="showRefuse ? 'refuse_div' : ''">
      <view class="label">
        <view>入会立享超值特权</view>
      </view>
      <view class="privilege-items">
        <view v-for="(item, index) in privilegeItems" :key="index">
          <image :src="item.icon" />
          <label class="leading-none">{{ item.label }}</label>
        </view>
      </view>
      <view class="read-me">
        请仔细阅读如下协议<br />
        如不同意相关协议内容，您应立即停止注册
      </view>
    </view>
    <view class="agree" :class="showRefuse ? 'agree_div' : ''">
      <view class="flex items-center px-22px">
        <template>
          <image
            v-if="iAgree"
            class="i-agree"
            :src="ossImg('register/checkbox.png')"
            @click.stop="iAgree = false"
          />
          <view v-else class="i-agree" @click.stop="isAgree"> </view>
        </template>
        <view class="agree-content">
          同意
          <view class="link" @click="toPage">隐私声明 </view
          >，包括收集我的信息作促销广告推送及数据分析等
        </view>
      </view>
      <button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
        即刻入会
      </button>
      <view v-if="showRefuse" class="refuse_btn" @click="backLast"
        >暂不入会，直接参与</view
      >
    </view>
  </view>


</template>

<script setup>
import { ossImg } from "@/utils/utils";
import {
  bindPhone,
  wechatUserPhone,
  accessLogAdd,
  userLogin,
} from "@/services/utils";
import { getSettingMall } from "@/services/home";
import { onLoad, onShow, onUnload, onHide } from "@dcloudio/uni-app";
import { ref } from "vue";
import { message, generateSign, randomString, debounce } from "@/utils/utils";
import { updateInfo } from "@/services/biscuit";
import { logger } from "@/utils/log";
import privacyPopup from "@/components/privacy-popup";

let enterTime = "";
let outTime = "";
let stayTime = "";

const showRefuse = ref(false);
const code_Q4 = ref("");
const Q4_from = ref();

onLoad(async (options) => {
  console.log("register----", options);

  if (["Q4"].includes(options.tag)) {
    showRefuse.value = true;
    code_Q4.value = options.code;
    Q4_from.value = options.from;
  }
});

onShow(async () => {
  // 用户进入时间
  getApp().getUserInfo();
  enterTime = new Date();
  getApp().accessLogAdd();
});

onHide(() => {
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime.getTime() - enterTime.getTime()) / 1000;
  if (showRefuse.value) {
    getApp().emdlz2(
      "track",
      "event",
      "q4_onecodecampaign_join_page",
      "view",
      "join_page",
      "(viewtime)"
    );
  } else {
    getApp().emdlz2(
      "track",
      "event",
      "member_page",
      "view",
      "member_register_page",
      stayTime
    );
  }
});

onUnload(() => {
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime.getTime() - enterTime.getTime()) / 1000;
  if (showRefuse.value) {
    getApp().emdlz2(
      "track",
      "event",
      "q4_onecodecampaign_join_page",
      "view",
      "join_page",
      "(viewtime)"
    );
  } else {
    getApp().emdlz2(
      "track",
      "event",
      "member_page",
      "view",
      "member_register_page",
      stayTime
    );
  }
});

const toPage = () => {
  if (showRefuse.value) {
    getApp().emdlz2(
      "track",
      "event",
      "q4_onecodecampaign_join_page",
      "click",
      "policy_rules",
      ""
    );
  } else {
    getApp().emdlz2(
      "track",
      "event",
      "member_page",
      "click",
      "privacy_statement",
      ""
    );
  }
  linkTo("/pages/privacyPolicy/index");
};

const iAgree = ref(false);
const isAgree = () => {
  if (showRefuse.value) {
    getApp().emdlz2(
      "track",
      "event",
      "q4_onecodecampaign_join_page",
      "click",
      "agree_policy1",
      ""
    );
  }
  iAgree.value = true;
};
const privilegeItems = ref([
  { label: "购物多倍积分", icon: ossImg("register/no1icon.png") },
  { label: "入会礼", icon: ossImg("register/no2icon.png") },
  { label: "积分商城礼品兑换", icon: ossImg("register/no3icon.png") },
  { label: "复购礼", icon: ossImg("register/no4icon.png") },
  { label: "生日礼", icon: ossImg("register/no5icon.png") },
  { label: "美食知识", icon: ossImg("register/no6icon.png") },
]);

const bindPhoneFun = debounce(
  async (phone) => {
    const bindPhoneRes = await bindPhone({ phone });
    if (bindPhoneRes?.code === 200) {
      switch (bindPhoneRes?.data) {
        case -1:
          message("手机号已被注册，请更换其它手机号");
          break;

        // 绑定成功
        case 1:
          message("绑定成功！");
          bindPhoneSuccess(phone);
          break;

        case 0:
          getApp()
            .getUserInfo()
            .then((res) => {
              if (!res.phone) {
                logger.warn(
                  "注册会员绑定手机号接口，绑定异常：",
                  bindPhoneRes?.data
                );
                message("绑定异常");
              } else {
                bindPhoneSuccess(phone);
              }
            })
            .catch(() => {
              logger.warn(
                "注册会员绑定手机号接口，绑定异常：",
                bindPhoneRes?.data
              );
              message("绑定异常");
            });

          break;

        default:
          logger.warn("注册会员绑定手机号接口，其他data值：", bindPhoneRes);
          break;
      }
    } else {
      logger.error("注册会员绑定手机号接口错误回调：", bindPhoneRes);
      console.log(bindPhoneRes);
      message("绑定失败");
    }
  },
  500,
  false
);

const getPhoneNumber = async ({ detail }) => {
  if (!iAgree.value) return message("请先同意相关协议!");
  if (showRefuse.value) {
    getApp().emdlz2(
      "track",
      "event",
      "q4_onecodecampaign_join_page",
      "click",
      "join_member",
      ""
    );
  } else {
    getApp().emdlz2("track", "event", "member_page", "click", "join_now", "");
  }
  if (!detail?.code) return;

  const wxUserPhoneRes = await wechatUserPhone({ code: detail.code });
  if (wxUserPhoneRes?.data?.countryCode !== "86")
    return message("目前仅支持中国大陆地区手机号");
  const phone = wxUserPhoneRes?.data?.purePhoneNumber;
  bindPhoneFun(phone);
};

const bindPhoneSuccess = (phone) => {
  console.log("phone---------");
  const body = {
    wxScene: uni.getLaunchOptionsSync().scene,
    scene: uni.getLaunchOptionsSync().query.scene
      ? uni.getLaunchOptionsSync().query.scene
      : uni.getStorageSync("SCENE") || "",
    type: "register",
    channelId: "",
    nonce: randomString(),
    timestamp: parseInt(new Date().getTime() / 1000),
  };

  uni.request({
    url: `${process.env.BASE_API}s-mall/api/access-log/loginaccess`,
    method: "post",
    data: {
      ...body,
      ...{ sign: generateSign(body) },
    },
    header: {
      Authorization: uni.getStorageSync("TOKEN")
        ? `Bearer ${uni.getStorageSync("TOKEN")}`
        : "",
    },
  });

  getApp().sr().track("register_wxapp", {});
  getApp().emdlz2(
    "set",
    "user",
    "memberid",
    getApp().globalData.user?.memberScore?.memberId ?? ""
  );
  getApp().globalData.user.needBindPhone = false;
  // 全局数据写入phone
  getApp().globalData.user.phone = phone;

  // 优惠劵
  const { path, navigate, redirect, navigateBack } = JSON.parse(
    uni.getStorageSync("REDIRECT_URI") || "{}"
  );
  console.log("path----------", path);
  if (path === "/personalPages/coupon/coupon") {
    getApp().emdlz2(
      "track",
      "event",
      "coupons_redemption_code",
      "pagejump",
      "jump_back",
      ""
    );
    uni.navigateBack({ delta: 1 });
    return;
  }

  // 获取当前页面的实例
  let pages = getCurrentPages();
  // 获取的才是当前页面实例
  let currentPage = pages[pages.length - 1];
  if (currentPage.options.backType) return backH5();
  if (currentPage.options.backSpring) return toSpring();
  if (["PANDA202301", "scanCode"].includes(currentPage.options.tag))
    return uni.navigateBack({ delta: 1 });
  if (["Q4"].includes(currentPage.options.tag)) {
    console.log("currentPage.options.from", Q4_from.value);
    if (Q4_from.value == "index") {
      uni.redirectTo({
        url: "/pages/2023oreocore/index?code=" + code_Q4.value,
      });
    } else {
      uni.redirectTo({
        url: "/campaign/pages/oreoQ4/scanCodeInput?code=" + code_Q4.value,
      });
    }
  }

  if (redirect) return uni.redirectTo({ url: path });
  if (navigate) return uni.navigateTo({ url: path });
  if (navigateBack) return uni.navigateBack({ delta: 1 });
  uni.switchTab({ url: path });
};

const backLast = () => {
  getApp().emdlz2(
    "track",
    "event",
    "q4_onecodecampaign_join_page",
    "click",
    "join_activity",
    ""
  );
  if (Q4_from.value == "index") {
    uni.redirectTo({
      url: "/pages/2023oreocore/index?code=" + code_Q4.value,
    });
  } else {
    uni.redirectTo({
      url: "/campaign/pages/oreoQ4/scanCodeInput?code=" + code_Q4.value,
    });
  }
};
const backH5 = async () => {
  if (!uni.getStorageSync("TOKEN")) {
    // 静默拿取微信用户的 openId 与 unionId 信息
    uni.login({
      provider: "weixin",
      success: async (res) => {
        console.log(res);
        const loginParam = {
          type: 1,
        };
        loginParam.code = res?.code;
        loginParam.nickName = "微信用户";
        loginParam.avatar = ossImg("personal/moren_avatar.png");
        const { data } = await userLogin(loginParam);
        uni.setStorageSync("TOKEN", data?.accessToken);
        uni.setStorageSync("OPENID", data?.openId);
        uni.setStorageSync("UNIONID", data?.unionId);
        getApp().emdlz2("set", "user", "openid", data?.openId);
        getApp().emdlz2("set", "user", "unionId", data?.unionId);
        getApp().sr().track("login_wxapp", {
          // more...
        });

        const getUrl = await getSettingMall({ key: "third_activity" });
        const H5_KEY = uni.getStorageSync('ONPACK_H5_KEY')
        if (getUrl?.code === 200) {
          setTimeout(() => {
            if (H5_KEY === '2025Spring') {
              uni.removeStorageSync('ONPACK_H5_KEY')
              uni.redirectTo({
                url: `/campaign/pages/2025Spring/index?accesstoken=${data?.accessToken}&openId=${data?.openId}&isRegistered=true`,
              });
            } else {
              uni.redirectTo({
                url: `/pages/webView/luckyDrawH5?webSrc=${getUrl?.data?.lotteryUrl}&accesstoken=${data?.accessToken}&openId=${data?.openId}&isRegistered=true`,
              });
            }
          }, 1500);
        }

        getApp().sr().track("login_wxapp", {
          // more...
        });
      },
    });
  } else {
    if (
      getApp().globalData.user.nickname === null ||
      getApp().globalData.user.nickname === "" ||
      getApp().globalData.user.nickname === undefined
    ) {
      const up = await updateInfo({
        nickname: "微信用户",
        icon: ossImg("personal/moren_avatar.png"),
      });
    }
    const getUrl = await getSettingMall({ key: "third_activity" });
    const H5_KEY = uni.getStorageSync('ONPACK_H5_KEY')
    if (getUrl?.code === 200) {
      setTimeout(() => {
        if (H5_KEY === '2025Spring') {
          uni.removeStorageSync('ONPACK_H5_KEY')
          uni.redirectTo({
            url: `/campaign/pages/2025Spring/index?accesstoken=${uni.getStorageSync(
              "TOKEN"
            )}&openId=${uni.getStorageSync("OPENID")}&isRegistered=true`,
          })
        } else {
          uni.redirectTo({
            url: `/pages/webView/luckyDrawH5?webSrc=${
              getUrl.data.lotteryUrl
            }&accesstoken=${uni.getStorageSync(
              "TOKEN"
            )}&openId=${uni.getStorageSync("OPENID")}&isRegistered=true`,
          });
        }
      }, 1500);
    }
  }
};

const linkTo = (url) => uni.navigateTo({ url });

const toSpring = () => {
  uni.redirectTo({
    url: `/campaign/pages/spring/index`,
  });
};
</script>

<style lang="less" scoped>
@import "@/static/css/theme.less";

.oreo-register {
  width: 100%;
  min-height: 705px;
  height: 100vh;
  background-color: white;
}

.privilege {
  box-sizing: border-box;
  padding: 70px 56px;
  background-color: #fff;

  .label {
    position: relative;
    font-size: 14px;
    color: @primary-color;
    display: flex;
    align-items: center;
    justify-content: center;
    line-height: 1;
    margin-bottom: 12px;

    view {
      width: 120px;
      text-align: center;
      background-color: white;
      position: relative;
      z-index: 2;
    }

    &::after {
      content: "";
      width: 100%;
      height: 1px;
      background-color: #1b5abd;
      position: absolute;
      z-index: 0;
    }
  }

  .privilege-items {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;

    > view {
      margin-bottom: 12px;
      color: #e2d2a3;
      font-size: 10px;
      text-align: center;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-direction: column;
      margin-right: 40px;
      width: 52px;

      &:nth-child(3n + 3) {
        margin-right: 0;
      }

      label {
        white-space: nowrap;
      }

      image {
        width: 52px;
        height: 52px;
        display: block;
        margin: 0;
        margin-bottom: 4px;
      }
    }
  }

  .read-me {
    color: #999999;
    font-size: 12px;
    text-align: center;
    padding: 14px 17px 0 17px;
    box-sizing: border-box;
  }
}
.refuse_div {
  padding: 18px 56px !important;
}

.agree {
  font-size: 12px;
  color: #777777;
  padding: 0 12px 12px 12px;
  box-sizing: border-box;
  background-color: #fff;

  .agree-content {
    word-break: break-all;
  }

  .link {
    color: #222222;
    display: inline-block;
    font-weight: bold;
    text-decoration: underline;
  }

  image.i-agree {
    background-color: @primary-color;
  }

  .i-agree {
    width: 16px;
    min-width: 16px;
    height: 16px;
    margin-right: 16px;
    border: 2px solid @primary-color;
    box-sizing: border-box;
  }

  button {
    width: 100%;
    height: 48px;
    margin-top: 10px;
    line-height: 48px;
    background: #1a5ac0;
    color: white;
    border-radius: 12px;
    font-size: 16px;

    &::after {
      border: none;
    }
  }
  .refuse_btn {
    height: 44px;
    line-height: 44px;
    text-align: center;
    font-size: 14px;
  }
}
.agree_div {
  padding: 0 12px 3px 12px !important;
}

image {
  display: block;

  &.oreo-header {
    width: 100%;
    height: 80px;
    position: relative;
    z-index: 11;
  }
}

.oreo-body {
  width: 100%;
  height: 175px;
  background-size: 100% 100%;
  background-position: bottom left;
  background-repeat: no-repeat;
  display: flex;
  box-sizing: border-box;
  align-items: center;
  flex-direction: column;
  text-align: center;
  letter-spacing: 1px;
  color: #1b5abd;

  image {
    width: 80px;
    height: 80px;
    margin-bottom: 10px;
    margin-top: 15px;
  }
}
</style>
